


var modelImgUrl='../../../images/';
let Tools = require('../../../js/Tools.js');
let requestManager = require('../../../js/requestsMode.js');
let sessionManager = require('../../../js/session.js');

Page({
    data:{
        addressId: "",
        shopArray : [],
        locationIcon:modelImgUrl+'location_icon.png',
        getPeopleName:"",
        phoneNumber:'',
        location:"",
        radioImg:modelImgUrl+'carChoseStyle.png',
        wayOfPay:1,
        senPrice:'3.00',
        allPrice:'102.00',
        price:'99.30',
        sendPrice:'0.00',
        sendTime:"2018-5-5",
        yourOrderNumber:2,
        allNumber:1,
        realityMoney:'',
        activityBoxWidth:"100%",
        animationTime:"transition: all 0s;",
        activityImg:modelImgUrl+"openActivity.png",
        windowType : true,
        giveShopping : [],/*赠品列表*/
        coupon_info:[],/*优惠券列表*/
        selectConpun : "未使用",
        selectCounpunId : "",
        ///赠品提示信息
        giveShopHint : "点击查看"
    },
    ///页面进入回调
    onLoad : function (data) {
        let shopArray = JSON.parse(data.shopArray);
        let shop_cart_ids = data.shop_cart_ids;
        if(shop_cart_ids){
            this.setData({
                shop_cart_ids : shop_cart_ids.split(',')
            })
        }
        let orderPrice = 0.0;
        for (var temIndex in shopArray) {
            var shop = shopArray[temIndex];
            shop["totalPrice"] = shop.number * shop.space_price;
            orderPrice += shop["totalPrice"];
        }
        orderPrice = orderPrice.toFixed(2);
        this.setData({
                shopArray : shopArray,
                realityMoney : String(orderPrice),
                price : String(orderPrice),

            });
    },
    onShow:function(){
        this.requestDefaultAddress();
    },
    setDefaultAddress:function(){
        wx.navigateTo({
            url:'../addressManager/addressManager'
        });
    },
    /*打开弹窗*/
    useCoupon: function (e) {
        let type = e.currentTarget.dataset.type;
        let windowType = true;
       /* type == coupon代表显示优惠券，shopping代表查看商品*/
        if(type == 'shopping'){
            windowType = false;
        }
        this.setData({
            activityBoxWidth:'0',
            animationTime:"transition: all 0.3s;",
            windowType :windowType
        });

        /*操作下边*/
    },

    /*点击优惠券操作，即代表使用此优惠券*/
    useThisCoupon:function(e){
        var selectCoupon = e.currentTarget.dataset.item;
        let lastPayMoney = this.data.lastPayMoney;
        if (selectCoupon.face_value)
        {
            this.setData(
                {
                    selectConpun : "-" + selectCoupon.face_value,
                    selectCounpunId : selectCoupon.id,
                    lastPayMoney : (parseFloat(lastPayMoney) - parseFloat(selectCoupon.face_value)).toFixed(2)
                }
            );
        }
        this.closeWindow();

    },
    /*关闭弹窗*/
    closeWindow:function(){
        this.setData({
            activityBoxWidth:'100%',
            animationTime:"transition: all 0.3s;"
        })
    },
    //请求默认收货地址
    requestDefaultAddress : function () {
        let  that = this;
        Tools.showLoaddingDefault();
        requestManager.sendRequest("member/detail","POST",{},{sKey:sessionManager.get("sKey")}).then(
            function (requestSucessRes) {
               let  status = requestSucessRes.data.code;
                let memberAddressId = requestSucessRes.data.data.member_addressid;
                if( memberAddressId == 0){
                    Tools.hideLoaddingToast();
                    wx.showModal({
                        title: '提示',
                        content: '请先添加收货地址',
                        success: function(res) {
                            if (res.confirm) {
                                ///跳转到添加地址里面
                                wx.navigateTo({
                                    url:'../addAddress/addAddress'
                                });
                            } else if (res.cancel) {
                            }
                        }
                    });
                }else{
                    if (status == 200) {
                        ///请求成功
                        Tools.hideLoaddingToast();
                        let resultData = requestSucessRes.data.data;
                        that.setData(
                            {
                                getPeopleName :  resultData.consignee,
                                phoneNumber : resultData.mobile,
                                location : resultData.address_full,
                                addressId : resultData.member_addressid
                            }
                        );
                        that.reuqestOrderPreViewInfo();
                    }else if(status == 0) {
                        ///没有默认地址
                        Tools.hideLoaddingToast();
                        wx.showModal({
                            title: '提示',
                            content: '请先添加收货地址',
                            success: function(res) {
                                if (res.confirm) {
                                    ///跳转到添加地址里面
                                    wx.navigateTo({
                                        url:'../addAddress/addAddress'
                                    });
                                } else if (res.cancel) {
                                }
                            }
                        });
                    } else {
                        Tools.showErrorToast(requestSucessRes.data.message);
                    }
                }
            },function (requestFailRes)
            {
                Tools.showWrongNetWorkToast();
            }
        );
    },
    ////请求订单预览信息
    reuqestOrderPreViewInfo : function () {
        Tools.showLoaddingDefault();
        let that = this;
        let goodsInfo = this.getGoodsInfo();
        ///开始网络请求
        requestManager.sendRequest("order/available-activity","POST",{"goods_info":JSON.stringify(goodsInfo)},{sKey:sessionManager.get("sKey")}).then(
            function (requestSucess) {
                ///请求成功
                let  statusCode = requestSucess.data.code;
                if (statusCode == 200) {
                    Tools.hideLoaddingToast();
                    let  resultData = requestSucess.data.data;
                    if (!resultData.coupon_list.length) {
                        ///没有可用优惠券
                        that.setData(
                            {
                                selectConpun : "暂无优惠券"
                            }
                        );
                    }
                    if (!resultData.goods_give_list.length) {
                        ///没有赠品
                        that.setData({
                                giveShopHint : "暂无赠品"
                            });
                    }
                    that.setData({
                            sendTime : resultData.expect_time,
                            sendPrice : resultData.freight,
                            coupon_info : resultData.coupon_list,
                            giveShopping : resultData.goods_give_list
                        });
                    if(resultData.fullCut.face_value){
                        that.setData({
                            lastPayMoney : (parseFloat(resultData.freight) + parseFloat(that.data.realityMoney)).toFixed(2) - parseFloat(resultData.fullCut.face_value).toFixed(2),
                            face_value   : resultData.fullCut.face_value
                        })
                    }else{
                        that.setData({
                            lastPayMoney : (parseFloat(resultData.freight) + parseFloat(that.data.realityMoney)).toFixed(2),
                            face_value   : 0
                        })
                    }
                }else if(statusCode == -1){
                    Tools.showErrorToast("库存不足");
                    that.setData({
                        acceptToPay:false
                    })
                }else {
                    ///请求失败
                    Tools.showErrorToast(requestSucess.data.message);
                }
            },
            function (requestFail) {
                Tools.showWrongNetWorkToast();
            }
        );
    },
    choseWayOfPay:function(e){
        let id= e.currentTarget.dataset.id;
        this.setData({
            wayOfPay:id
        })
    },
    getGoodsInfo : function () {

        let goodsInfo = [];
        for (var tempIndex in this.data.shopArray)
        {
            var shop = this.data.shopArray[tempIndex];
            var sendJson = {
                "type_id" :shop.type_id,
                "total_fee" :shop.totalPrice.toFixed(2)
            }
            goodsInfo.push(sendJson);
        }
        return goodsInfo;
    },
    goToPay:function(){
        if(  this.data.acceptToPay != false ){
            this.payOrderGenerateRequest();
        }
    },
    payOrderGenerateRequest : function () {
        let goodsInfo = [];
        for (var tempIndex in this.data.shopArray) {
            var shop = this.data.shopArray[tempIndex];
            var sendJson = {
                "goods_id" :shop.goods_id,
                "space_id" :shop.space_id,
                "number": shop.number
            };
            goodsInfo.push(sendJson);
        }
        let payType = 3;
        if (this.data.wayOfPay == 0) {
            payType = 3;
        }else if(this.data.wayOfPay == 1) {
            payType = 1;
        }
        Tools.showLoaddingToast("正在生成订单");
        var  coupon_id = this.data.selectCounpunId;
        if (!coupon_id) {
            coupon_id = "0";
        }
        let  that = this;
        let requestBody = {"goods_info" : JSON.stringify(goodsInfo),"coupon_id":coupon_id,"address_id":this.data.addressId,"pay_type":payType};
        if(that.data.shop_cart_ids){
            requestBody['shop_cart_ids'] = that.data.shop_cart_ids.toString();
        }
        let userSkey = sessionManager.get("sKey");
        requestManager.sendRequest("order/create","POST",requestBody,{sKey:userSkey}).then(
            function (requestSucess) {
                let statusCode = requestSucess.data.code;
                if (statusCode == 200) {
                    ///订单创建好了
                    Tools.hideLoaddingToast();
                    //console.log("requestSucess.data.data",requestSucess.data.data);
                   // that.jumpOrderDeatail(requestSucess.data.data);
                    let requestGetOrderId = requestSucess.data.data.order_id;
                    that.setData({
                        requestGetOrderId :requestGetOrderId
                    });
                    if(that.data.wayOfPay == 1){
                        wx.navigateTo({
                            url: '../orderDetailed_payByweiChart/orderDetailed_payByweiChart?&order_id='+that.data.requestGetOrderId
                        });
                    }else{
                        wx.navigateTo({
                            url: '../orderDetailed_payAfterGet/orderDetailed_payAfterGet?&order_id='+that.data.requestGetOrderId
                        });
                    }

                }else {
                    ///订单创建失败
                    Tools.showErrorToast(requestSucess.data.message);
                }
            },function (requestWrong) {
                Tools.showWrongNetWorkToast();
            }
        )
    },
    jumpOrderDeatail : function (orderData) {
        wx.requestPayment({
            'timeStamp': orderData.timeStamp,
            'nonceStr': orderData.nonceStr,
            'package': orderData.package,
            'signType': 'MD5',
            'paySign': orderData.paySign,
            'success':function(res){
                Tools.showSuccessInfoToast("支付成功");
            },
            'fail':function(res){
                Tools.showErrorToast("支付失败");
            }
        });
        // if( this.data.wayOfPay == 0){
        //     wx.navigateTo({
        //         url:'../orderDetailed_payAfterGet/orderDetailed_payAfterGet'
        //     });
        // }else{
        //     wx.navigateTo({
        //         url:'../orderDetailed_payByweiChart/orderDetailed_payByweiChart?orderInfo='+JSON.stringify(orderData)
        //     });
        // }
    }
});